package com.foodcommunity.service.impl;

import com.foodcommunity.entity.Category;
import com.foodcommunity.mapper.CategoryMapper;
import com.foodcommunity.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectAll();
    }

    @Override
    public Category getCategoryById(Long id) {
        return categoryMapper.selectById(id);
    }
    
    @Override
    public List<Map<String, Object>> getCategoriesWithPostCount() {
        // 获取所有分类
        List<Category> categories = categoryMapper.selectAll();
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 为每个分类添加文章数量
        for (Category category : categories) {
            Map<String, Object> categoryMap = new HashMap<>();
            categoryMap.put("id", category.getId());
            categoryMap.put("name", category.getName());
            categoryMap.put("description", category.getDescription());
            
            // 获取分类的文章数量
            int postCount = categoryMapper.countPostsByCategory(category.getId());
            categoryMap.put("postCount", postCount);
            
            // 添加分类图片URL
            categoryMap.put("imageUrl", getCategoryImageUrl(category.getName()));
            
            result.add(categoryMap);
        }
        
        return result;
    }
    
    /**
     * 根据分类名称获取图片URL
     */
    private String getCategoryImageUrl(String categoryName) {
        Map<String, String> imageMap = new HashMap<>();
        imageMap.put("中餐", "https://images.unsplash.com/photo-1563245372-f21724e3856d");
        imageMap.put("西餐", "https://images.unsplash.com/photo-1504674900247-0877df9cc836");
        imageMap.put("日料", "https://images.unsplash.com/photo-1579871494447-9811cf80d66c");
        imageMap.put("韩餐", "https://images.unsplash.com/photo-1590301157890-4810ed352733");
        imageMap.put("甜点", "https://images.unsplash.com/photo-1488477181946-6428a0291777");
        imageMap.put("饮品", "https://images.unsplash.com/photo-1544145945-f90425340c7e");
        
        return imageMap.getOrDefault(categoryName, "https://images.unsplash.com/photo-1563245372-f21724e3856d");
    }
} 